package dhm.com.hpx.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.hpx.R;
import dhm.com.hpx.base.BaseActivity;
import dhm.com.hpx.base.Presenter.PressenterImpl;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.Bean;
import dhm.com.hpx.entity.ExtensionlistBeam;
import dhm.com.hpx.entity.FavoriteArticleBean;
import dhm.com.hpx.entity.GetUserInfoBean;
import dhm.com.hpx.utils.SpUtils;
import dhm.com.hpx.utils.WXUtil;
import dhm.com.hpx.utils.mapapi.Util;

public class ExtensionarticleActivity extends BaseActivity implements LoginContract.IView {

    @BindView(R.id.article_title)
    TextView articleTitle;
    @BindView(R.id.num)
    TextView num;
    @BindView(R.id.image)
    SimpleDraweeView image;
    @BindView(R.id.nick)
    TextView nick;
    @BindView(R.id.collection)
    ImageView collection;
    @BindView(R.id.job)
    TextView job;
    @BindView(R.id.webview)
    WebView ticketWb;
    @BindView(R.id.z)
    TextView z;
    @BindView(R.id.g)
    TextView g;
    @BindView(R.id.mingp)
    SimpleDraweeView mingp;

    private PressenterImpl pressenter;
    private String uid;
    private String extension_id;
    private IWXAPI api;
    private ExtensionlistBeam extensionlistBeam;
    boolean iscollection = false;

    private String userType;

    @Override
    protected int getLayout() {
        return R.layout.activity_extensionarticle;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        userType = SpUtils.getString(this, "userType");
        pressenter=new PressenterImpl();
        pressenter.attachView(this);
        uid = SpUtils.getString(this, "uid");
        api = WXAPIFactory.createWXAPI(this, Constant.Wx_APP_ID, false);
        extension_id = getIntent().getStringExtra("extension_id");

        Map<String,String> map=new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("extension_id",extension_id);
        map.put("uid",uid);
        pressenter.sendMessage(this,Constant.extension_info,map, ExtensionlistBeam.class);


    }

    private  Bitmap mBitmap;
    @Override
    protected void initData() {

    }
    int page = 1;
    @OnClick({R.id.back, R.id.phone, R.id.updata, R.id.tui, R.id.collection})
    public void onViewClicked(View view) {
        Map<String,String> map;
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.phone:
                Toast.makeText(this, "拨打电话功能需要分享到微信后才能生效！", Toast.LENGTH_SHORT).show();
                break;
            case R.id.updata:
                Intent intent = new Intent(this, MyinfoActivity.class);
                startActivity(intent);
                break;
            case R.id.tui://初始化一个WXWebpageObject，填写url

                switch (userType) {
                    case "0":
                        Toast.makeText(this, "暂无权限查看，请升级会员" , Toast.LENGTH_SHORT).show();
                        break;
                    case "1":
                    case "2":
                        Toast.makeText(this, "暂无权限查看，请升级年卡会员", Toast.LENGTH_SHORT).show();
                        break;
                    case "4":
                        Toast.makeText(this, "您的会员已过期" , Toast.LENGTH_SHORT).show();
                        break;
                    case "3":
                    case "5":
                    default:

                        if (extensionlistBeam==null){
                            Toast.makeText(this, "正在加载，请稍后...", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        WXWebpageObject webpage = new WXWebpageObject();
//                webpage.webpageUrl = "http://www.quqike.cn/appapi/appletscode/getwxacode/uid/" + uid + "/type/1/article_id/8";
//                webpage.webpageUrl = "http://www.quqike.cn/appapi/extension/extension_article_info/uid/" + uid + "/extension_id/"+extension_id;
                        webpage.webpageUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Constant.urlappid+"&redirect_uri=" +
                                Constant.PATH+"appapi/extension/shouquan/uid/" + extensionlistBeam.getData().getUser_id() + "/type/4/target_id/"+extension_id +
                                "&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect";

//用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
                        final WXMediaMessage msg = new WXMediaMessage(webpage);
                        msg.title = extensionlistBeam.getData().getTitle();
                        msg.description = extensionlistBeam.getData().getDesc();

                        if (extensionlistBeam.getData().getCover_pic()==null||extensionlistBeam.getData().getCover_pic().equals("")){
                            Bitmap thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.main_yao);
                            msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

//构造一个Req
                            SendMessageToWX.Req req = new SendMessageToWX.Req();
                            req.transaction = buildTransaction("webpage");
                            req.message = msg;
                            req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前只支持会话
//调用api接口，发送数据到微信
                            api.sendReq(req);
                        }else {
                            initNetWorkImage(api,ExtensionarticleActivity.this,Constant.PATH+extensionlistBeam.getData().getCover_pic(),"weChat",msg);
                        }



                        map=new HashMap<>();
                        map.put("token",Constant.TOKEN);
                        map.put("target_id",extension_id);
                        map.put("uid",uid);
                        map.put("type","4");
                        pressenter.sendMessage(ExtensionarticleActivity.this,Constant.add_share,map, Bean.class);
                }



                break;
            case R.id.collection:

                if (iscollection) {
                    //收藏取消收藏

                    page = 1;

                    map = new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("uid", uid);
                    map.put("page", page + "");
                    pressenter.sendMessage(this, Constant.listArticlesQuery, map, FavoriteArticleBean.class);


                } else {
                    //未收藏收藏
                    map = new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("uid", uid);
                    map.put("type", "4");
                    map.put("id", extension_id);
                    pressenter.sendMessage(this, Constant.add, map, Bean.class);
                }

                break;
            default:
        }
    }


    @SuppressLint("StaticFieldLeak")
    public static void initNetWorkImage(final IWXAPI wxapi, final Context context, final String imgUrl, final String flag, final WXMediaMessage msg) {
        new AsyncTask<Void, Void, Bitmap>() {

            @Override
            protected Bitmap doInBackground(Void... voids) {
                Bitmap bitmap = null;
                try {
                    bitmap = Glide.with(context)
                            .asBitmap()
                            .load(imgUrl)
                            .submit(100, 100).get();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return bitmap;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                msg.thumbData = WXUtil.bitmap2Bytes(bitmap, 150);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("webpage");
                req.message = msg;
                if (flag.equals("weChat")) {
                    req.scene = SendMessageToWX.Req.WXSceneSession;
                } else if (flag.equals("friends")) {
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                }
                wxapi.sendReq(req);
            }
        }.execute();
    }

    private static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    @Override
    public void requesta(Object data) {
        if (data instanceof ExtensionlistBeam){
            extensionlistBeam = (ExtensionlistBeam) data;
            if (extensionlistBeam.getCode()==1){
                articleTitle.setText(extensionlistBeam.getData().getTitle());
                if(uid.equals(extensionlistBeam.getData().getUser_id()+"")){
                    collection.setVisibility(View.GONE);
                }else {
                    collection.setVisibility(View.VISIBLE);
                    if (extensionlistBeam.getData().getIs_favorites() == 1) {
                        iscollection = true;
                        collection.setImageResource(R.mipmap.collections);
                    } else {
                        collection.setImageResource(R.mipmap.collection);
                        iscollection = false;
                    }
                }

                WebSettings webSettings = ticketWb.getSettings();
                webSettings.setUseWideViewPort(true);//是否支持双击缩放网页操作(wap网页不支持)
                webSettings.setJavaScriptEnabled(true);//是否支持JavaScript

                webSettings.setSupportZoom(true);
                webSettings.setJavaScriptEnabled(true);
                webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
                webSettings.setBuiltInZoomControls(true);//support zoom
                webSettings.setUseWideViewPort(true);//關鍵點
                webSettings.setLoadWithOverviewMode(true);
//blog.csdn.net/iteye_20362/article/details/82541254
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (!TextUtils.isEmpty(Constant.PATH+extensionlistBeam.getData().getCover_pic())) { //网络图片
                                // 对资源链接
                                URL url = new URL(Constant.PATH+extensionlistBeam.getData().getCover_pic());
                                //打开输入流
                                InputStream inputStream = url.openStream();
                                //对网上资源进行下载转换位图图片
                                mBitmap = BitmapFactory.decodeStream(inputStream);
                                inputStream.close();
                            }
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

                DisplayMetrics metrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metrics);
                int mDensity = metrics.densityDpi;

                if (mDensity == 240) {
                    webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
                } else if (mDensity == 160) {
                    webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
                } else if (mDensity == 120) {
                    webSettings.setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
                } else if (mDensity == DisplayMetrics.DENSITY_XHIGH) {
                    webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
                } else if (mDensity == DisplayMetrics.DENSITY_TV) {
                    webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
                }
                ticketWb.loadUrl(extensionlistBeam.getData().getLink());
                mingp.setImageURI(Constant.PATH+extensionlistBeam.getData().getWechat_card());

            }
            Map<String, String> map = new HashMap<>();
            map.put("token", Constant.TOKEN);
            map.put("uid", extensionlistBeam.getData().getUser_id()+"");
            pressenter.sendMessage(this, Constant.get_userinfo, map, GetUserInfoBean.class);

        }else if (data instanceof GetUserInfoBean) {
            GetUserInfoBean getUserInfoBean = (GetUserInfoBean) data;
            if (getUserInfoBean.getCode() == 1) {
                image.setImageURI(Constant.PATH + getUserInfoBean.getData().getHeadsmall());
                job.setText("专注" + getUserInfoBean.getData().getBusiness() + "，欢迎前来咨询。");
                g.setText("专注" + getUserInfoBean.getData().getBusiness() + "，欢迎前来咨询。");
                nick.setText(getUserInfoBean.getData().getUser_nickname());
            }
        }else if (data instanceof FavoriteArticleBean) {
            FavoriteArticleBean favoriteArticleBean = (FavoriteArticleBean) data;
            if (favoriteArticleBean.getCode() == 1) {
                page++;
                boolean iscontinue=true;
                for (int i = 0; i < favoriteArticleBean.getData().size(); i++) {
                    if (extension_id.equals(favoriteArticleBean.getData().get(i).getArticleId() + "")) {
                        extension_id = favoriteArticleBean.getData().get(i).getFavoriteId() + "";
                        iscontinue=false;
                        Map<String, String> map = new HashMap<>();
                        map.put("token", Constant.TOKEN);
                        map.put("uid", uid);
                        map.put("type", "4");
                        map.put("cid", extension_id);
                        pressenter.sendMessage(this, Constant.cancel, map, Bean.class);
                        return;
                    }
                }

                if (iscontinue){
                    Map<String, String> map = new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("uid", uid);
                    map.put("page", page + "");
                    pressenter.sendMessage(this, Constant.listArticlesQuery, map, FavoriteArticleBean.class);
                }

            }
        }else if (data instanceof Bean) {
            Bean bean = (Bean) data;
            Toast.makeText(this, bean.getMessage(), Toast.LENGTH_SHORT).show();
            if (bean.getCode() == 1) {

                if (bean.getMessage().equals("收藏成功")) {
                    iscollection = true;
                    collection.setImageResource(R.mipmap.collections);
                } else {
                    iscollection = false;
                    collection.setImageResource(R.mipmap.collection);
                }
            }


        }
    }

    @Override
    public void fail(String error) {

    }
}
